package com.ssy.lingxi.purchase.serviceimpl;

import cn.hutool.core.collection.CollectionUtil;
import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.common.utils.CollectionPageUtil;
import com.ssy.lingxi.component.rabbitMQ.constants.MessageConstants;
import com.ssy.lingxi.contract.api.feign.PurchaseInquiryControllerFeign;
import com.ssy.lingxi.contract.api.model.vo.request.PurchaseInquiryAddVO;
import com.ssy.lingxi.message.api.constant.MessageTemplateCode;
import com.ssy.lingxi.message.api.constant.MessageTitle;
import com.ssy.lingxi.platform.manage.api.feign.inner.SecretKeyControllerFeign;
import com.ssy.lingxi.platform.manage.api.model.dto.secret.CheckPasswordDTO;
import com.ssy.lingxi.purchase.api.common.OrderConstant;
import com.ssy.lingxi.purchase.api.dto.request.*;
import com.ssy.lingxi.purchase.api.dto.request.purchase.PurchaseInquiryListRequest;
import com.ssy.lingxi.purchase.api.dto.request.purchase.QuotedPriceInfoRequest;
import com.ssy.lingxi.purchase.api.dto.response.AwardInfoResponse;
import com.ssy.lingxi.purchase.api.dto.response.BiddingExternalWorkStateEnumResponse;
import com.ssy.lingxi.purchase.api.dto.response.CountryAreaResponse;
import com.ssy.lingxi.purchase.api.dto.response.PriceParityDetailsResponse;
import com.ssy.lingxi.purchase.api.dto.response.purchase.*;
import com.ssy.lingxi.purchase.api.enums.notice.PurchaseNoticeTypeEnum;
import com.ssy.lingxi.purchase.api.enums.purchase.*;
import com.ssy.lingxi.purchase.config.rabbitmq.OrderRbbitMqRequest;
import com.ssy.lingxi.purchase.config.rabbitmq.provider.RabbitMQProvider;
import com.ssy.lingxi.purchase.entity.notice.PurchaseNotice;
import com.ssy.lingxi.purchase.entity.purchaseinquiry.PurchaseInquiry;
import com.ssy.lingxi.purchase.entity.quotedprice.InteriorConfirmQuotedPriceLog;
import com.ssy.lingxi.purchase.entity.quotedprice.QuotedPrice;
import com.ssy.lingxi.purchase.entity.quotedprice.QuotedPriceDetails;
import com.ssy.lingxi.purchase.entity.quotedprice.QuotedPriceTurn;
import com.ssy.lingxi.purchase.repository.*;
import com.ssy.lingxi.purchase.repository.notice.PurchaseNoticeRepository;
import com.ssy.lingxi.purchase.service.ConfirmQuotedPriceService;
import com.ssy.lingxi.purchase.service.PurchaseInquiryService;
import com.ssy.lingxi.report.api.enums.ConfirmDemandQuotationOperateTypeEnum;
import com.ssy.lingxi.report.api.enums.DemandQuotationOperateTypeEnum;
import com.ssy.lingxi.report.api.enums.OperateDataSourceEnum;
import com.ssy.lingxi.workflow.api.model.contant.ProcessEnum;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskCompleteVO;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ConfirmQuotedPriceServiceImpl extends BasePurchaseInquiry implements ConfirmQuotedPriceService {

    @Resource
    PurchaseInquiryRepository purchaseInquiryRepository;
    @Resource
    QuotedPriceDetailsRepository quotedPriceDetailsRepository;
    @Resource
    QuotedPriceRepository quotedPriceRepository;
    @Resource
    SecretKeyControllerFeign secretKeyControllerFeign;
    @Resource
    InteriorConfirmQuotedPriceLogRepository interiorConfirmQuotedPriceLogRepository;
    @Resource
    PurchaseInquiryControllerFeign purchaseInquiryControllerFeign;
    @Resource
    RabbitMQProvider rabbitMQProvider;
    @Resource
    PurchaseInquiryService purchaseInquiryService;
    @Resource
    private PurchaseNoticeRepository purchaseNoticeRepository;
    @Resource
    QuotedPriceTurnRepository quotedPriceTurnRepository;

    /**
     * 报价查询
     */
    @Override
    public Wrapper<PageData<PurchaseInquiryListResponse>> list(PurchaseInquiryListRequest request, UserLoginCacheDTO sysUser) {
        Wrapper<PageData<PurchaseInquiryListResponse>> quotedPriceList = getPurchaseInquiryList(sysUser, request, ConfirmQuotedPriceQueryEnum.QUOTATION_INQUIRY.getType());
        if (ResponseCode.SUCCESS.getCode() == quotedPriceList.getCode() && !CollectionUtils.isEmpty(quotedPriceList.getData().getData())) {
            quotedPriceList.getData().getData().forEach(response -> {
                response.setButton(PurchaseInquiryListExternalWorkStateEnum.STAY_SUBMIT_OFFER.getState().equals(response.getExternalState()) ? ButtonEnum.PAY_ORDER.getStep() : ButtonEnum.CONFIRM_PAY_ORDER.getStep());
            });
        }
        return quotedPriceList;
    }

    /**
     * 调整报价截止时间
     */
    @Transactional
    @Override
    public Wrapper adjustTime(AdjustTimeRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        purchaseInquiry.setOfferEndTime(request.getIsNow() == 1 ? System.currentTimeMillis() : request.getQuotedPriceTime());
        purchaseInquiryRepository.saveAndFlush(purchaseInquiry);
        OrderRbbitMqRequest rbbitMqRequest = buildOrderRbbitMqRequest(purchaseInquiry, request);
        //立即截止
        if (request.getIsNow() == 1) {
            ExamineQuotedPriceBatchRequest batchRequest = new ExamineQuotedPriceBatchRequest();
            batchRequest.setId(purchaseInquiry.getId());
            purchaseInquiryService.examineQuotedPriceBatch(batchRequest);
            //保存待比价日志信息
            saveInteriorConfirmQuotedPriceLog(sysUser,PurchaseInquiryListInteriorWorkStateEnum.STAY_CONTRAST_PRICE.getName(),PurchaseInquiryListInteriorWorkStateEnum.CONTRAST_PRICE.getState()  ,PurchaseInquiryListInteriorWorkStateEnum.STAY_CONTRAST_PRICE.getState(),purchaseInquiry.getId(),"");
            return Wrapper.success();
        }
        //发送延迟mq
        rabbitMQProvider.sendDelayMessage(rbbitMqRequest, MessageConstants.PURCHASE_INQUIRY_DELAY_EXCHANGE, MessageConstants.PURCHASE_INQUIRY_DELAY_KEY, 2L);
        return Wrapper.success();
    }

    /**
     * build mq 发送信息
     *
     * @author lhq
     **/
    private OrderRbbitMqRequest buildOrderRbbitMqRequest(PurchaseInquiry purchaseInquiry, AdjustTimeRequest request) {
        OrderRbbitMqRequest rbbitMqRequest = new OrderRbbitMqRequest();
        rbbitMqRequest.setId(purchaseInquiry.getId());
        rbbitMqRequest.setMemberId(purchaseInquiry.getCreateMemberId());
        rbbitMqRequest.setMemberRoleId(purchaseInquiry.getCreateMemberRoleId());
        rbbitMqRequest.setExpirationTime(request.getQuotedPriceTime());
        return rbbitMqRequest;
    }

    /**
     * 报价详情
     */
    @Override
    public Wrapper<ConfirmQuotedPriceResponse> details(ConfirmQuotedPriceDetailsRequest request, UserLoginCacheDTO sysUser) {
        ConfirmQuotedPriceResponse response = new ConfirmQuotedPriceResponse();
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        BeanUtils.copyProperties(purchaseInquiry, response);
        response.setUrls(purchaseInquiry.getUrls());
        response.setTransactionUurls(purchaseInquiry.getTransactionUurls());
        response.setIsAreas(OrderConstant.State.START.equals(purchaseInquiry.getIsAreas()));
        response.setAreas(purchaseInquiry.getAreas().stream().map(temp -> {
            CountryAreaResponse countryArea = new CountryAreaResponse();
            BeanUtils.copyProperties(temp, countryArea);
            return countryArea;
        }).collect(Collectors.toList()));
        response.setExternalStateName(PurchaseInquiryListExternalWorkStateEnum.getName(purchaseInquiry.getExternalState()));
        response.setInteriorStateName(PurchaseInquiryListInteriorWorkStateEnum.getName(purchaseInquiry.getInteriorState()));
        //查询内部操作记录
        response.setInteriorLogs(getInteriorLog(purchaseInquiry.getId()));
        //查询内部流转状态
        response.setInteriorLogStates(getLogStateInterior(null, ProcessEnum.PURCHASE_CONFIRM_OFFER_INNER_VERIFY.getCode(), purchaseInquiry.getConfirmInteriorNextStep()));
        //查询外部操作记录
        response.setExternalLogs(getExternalLog(purchaseInquiry.getId()));
        //查询外部流转状态
        List<Long> roles = getRolesByPurchaseInquiry(purchaseInquiry.getId());
        response.setExternalLogStates(getLogStateResponse(ProcessEnum.PURCHASE_INQUIRY_OUTER_VERIFY.getCode(), purchaseInquiry.getExternalNextStep(), roles, purchaseInquiry.getCreateMemberRoleId()));
        return Wrapper.success(response);
    }

    /**
     * 立即比价
     */
    @Override
    public Wrapper<List<PriceParityDetailsResponse>> rightOffContrastPrice(ConfirmQuotedPriceDetailsRequest request, UserLoginCacheDTO sysUser) {
        //根据需求单获取报价单轮次
        List<QuotedPriceTurn> turns = quotedPriceTurnRepository.findByPurchaseInquiryIdAndTurnAndStatus(
                request.getId(), request.getTurn(), EnableDisableStatus.ENABLE.getCode()
        );
        if (CollectionUtils.isEmpty(turns)) {
            return Wrapper.success(new ArrayList<>());
        }

        //根据轮次的报价单ID获取报价单
        List<QuotedPrice> quotedPrices = quotedPriceRepository.findAllById(
                turns.stream().map(QuotedPriceTurn::getQuotedPriceId).collect(Collectors.toList())
        );
        if (CollectionUtils.isEmpty(quotedPrices)) {
            return Wrapper.success(new ArrayList<>());
        }

        //判断是否已经解密
        List<QuotedPrice> collect = quotedPrices.stream().filter(quotedPrice -> quotedPrice.getIsDecrypt().equals(OrderConstant.State.STOP)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(collect)) {
            return Wrapper.fail(ResponseCode.QUOTED_PRICE_NOT_DECRYPT);
        }

        //获取报价单物料信息
        List<QuotedPriceDetails> quotedPriceDetails = quotedPriceDetailsRepository.findAllByTurnAndQuotedPriceIdIn(request.getTurn(), quotedPrices.stream().map(QuotedPrice::getId).collect(Collectors.toList()), Sort.by("taxUnitPrice").ascending());
       //统计报价单比价信息
        return Wrapper.success(info(quotedPrices, quotedPriceDetails));
    }

    /**
     * 报价单详情
     */
    @Override
    public Wrapper<ConfirmQuotedPriceDetailsResponse> detailed(BaseDetailsRequest request, UserLoginCacheDTO sysUser) {
        QuotedPrice quotedPrice;
        if (!StringUtils.hasLength(request.getNumber())) {
            quotedPrice = quotedPriceRepository.findById(request.getId()).orElse(null);
        } else {
            quotedPrice = quotedPriceRepository.findByQuotedPriceNo(request.getNumber());
        }
        if (ObjectUtils.isEmpty(quotedPrice)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        if (OrderConstant.State.STOP.equals(quotedPrice.getIsDecrypt())) {
            return Wrapper.fail(ResponseCode.QUOTED_PRICE_NOT_DECRYPT);
        }
        ConfirmQuotedPriceDetailsResponse response = new ConfirmQuotedPriceDetailsResponse();
        BeanUtils.copyProperties(quotedPrice, response);
        response.setTel(quotedPrice.getTel());
        response.setContacts(quotedPrice.getContacts());
        response.setEnclosureUrls(quotedPrice.getEnclosureUrls());
        response.setExternalStateName(PurchaseInquiryListExternalWorkStateEnum.getName(quotedPrice.getExternalState()));

        //获取报价单轮次
        List<QuotedPriceTurn> quotedPriceTurnList = quotedPriceTurnRepository.findAllByQuotedPriceId(quotedPrice.getId(), Sort.by("id"));
        response.setQuotedPriceTurnList(
                quotedPriceTurnList.stream().map(a -> {
                    QuotedPriceTurnResp quotedPriceTurnResp = new QuotedPriceTurnResp();
                    BeanUtils.copyProperties(a, quotedPriceTurnResp);
                    return quotedPriceTurnResp;
                }).collect(Collectors.toList())
        );

        return Wrapper.success(response);
    }

    /**
     * 报价单详情-物料详情列表查询-分页
     */
    @Override
    public Wrapper<PageData<QuotedPriceProductResponse>> materielDetailed(MaterielDetailedRequest request, UserLoginCacheDTO sysUser) {
        QuotedPrice quotedPrice = quotedPriceRepository.findById(request.getId()).orElse(null);
        if (ObjectUtils.isEmpty(quotedPrice)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        if (OrderConstant.State.STOP.equals(quotedPrice.getIsDecrypt())) {
            return Wrapper.fail(ResponseCode.QUOTED_PRICE_NOT_DECRYPT);
        }
        Page<QuotedPriceDetails> page = quotedPriceDetailsRepository.findAllByQuotedPriceIdAndTurn(quotedPrice.getId(), request.getTurn(), PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("id").ascending()));
        List<QuotedPriceProductResponse> lsit = new ArrayList<>();
        if (page.getTotalElements() > 0) {
            lsit = page.getContent().stream().map(temp -> {
                QuotedPriceProductResponse response = new QuotedPriceProductResponse();
                BeanUtils.copyProperties(temp, response);
                return response;
            }).collect(Collectors.toList());
        }
        return Wrapper.success(new PageData<>(page.getTotalElements(), lsit));
    }

    /**
     * 待比价
     */
    @Override
    public Wrapper<PageData<PurchaseInquiryListResponse>> stayContrastPrice(PurchaseInquiryListRequest request, UserLoginCacheDTO sysUser) {
        Wrapper<PageData<PurchaseInquiryListResponse>> quotedPriceList = getPurchaseInquiryList(sysUser, request, ConfirmQuotedPriceQueryEnum.STAY_PRICE_PARITY.getType());
        if (ResponseCode.SUCCESS.getCode() == quotedPriceList.getCode() && !CollectionUtils.isEmpty(quotedPriceList.getData().getData())) {
            quotedPriceList.getData().getData().forEach(response -> {
                response.setButton(PurchaseInquiryListInteriorWorkStateEnum.STAY_CONTRAST_PRICE.getState().equals(response.getConfirmInteriorState()) ? ButtonEnum.ADD_DELIVER_GOODS_ORDER.getStep() : ButtonEnum.SUSPENSION_DELIVER_GOODS_ORDER.getStep());
            });
        }
        return quotedPriceList;
    }

    /**
     * 发起下轮报价
     */
    @Transactional
    @Override
    public Wrapper launchTurnQuotedPrice(AdjustTimeRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        //判断时间
        if (System.currentTimeMillis() >= request.getQuotedPriceTime()) {
            return Wrapper.fail(ResponseCode.OFFER_END_NOT_CURRENT_TIME);
        }
        List<QuotedPrice> quotedPrices = quotedPriceRepository.findAllByPurchaseInquiryId(purchaseInquiry.getId());
        purchaseInquiry.setOfferEndTime(request.getQuotedPriceTime());
        //发送mq消息
        OrderRbbitMqRequest rbbitMqRequest = new OrderRbbitMqRequest();
        rbbitMqRequest.setId(purchaseInquiry.getId());
        rbbitMqRequest.setMemberId(purchaseInquiry.getCreateMemberId());
        rbbitMqRequest.setMemberRoleId(purchaseInquiry.getCreateMemberRoleId());
        rbbitMqRequest.setExpirationTime(request.getQuotedPriceTime());
        rabbitMQProvider.sendDelayMessage(rbbitMqRequest, MessageConstants.PURCHASE_INQUIRY_DELAY_EXCHANGE, MessageConstants.PURCHASE_INQUIRY_DELAY_KEY, 2L);
        //执行外部工作流
        Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), purchaseInquiry.getId(), ProcessEnum.PURCHASE_INQUIRY_OUTER_VERIFY.getCode(), purchaseInquiry.getExternalNextStep(), purchaseInquiry.getExternalTaskId(), OrderConstant.Auditing.NOT_GO);
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            return taskResult;
        }
        purchaseInquiry.setTurn(purchaseInquiry.getTurn() + 1);
        purchaseInquiry.setCount(0);//重置有效报价次数
        purchaseInquiry.setExternalTaskId(taskResult.getData().getTaskId());
        purchaseInquiry.setExternalState(taskResult.getData().getStatus());
        purchaseInquiry.setExternalNextStep(taskResult.getData().getStep());
        saveExternalLog(sysUser, PurchaseInquiryExternalOperationRecordEnum.INITIATE_QUOTATION.getCHName(), taskResult.getData().getStatus(), purchaseInquiry.getId(), "");
        purchaseInquiryRepository.saveAndFlush(purchaseInquiry);
        if (!CollectionUtils.isEmpty(quotedPrices)) {
            quotedPrices.forEach(quotedPrice -> {
                quotedPrice.setExternalTaskId(taskResult.getData().getTaskId());
                quotedPrice.setExternalState(taskResult.getData().getStatus());
                quotedPrice.setExternalNextStep(taskResult.getData().getStep());
            });
            quotedPriceRepository.saveAll(quotedPrices);
        }
        reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_DEMAND_QUOTATION.getCode(), 0L, 0, 1L, ConfirmDemandQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode());
        reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.TRADE_DEMAND_QUOTATION.getCode(), 1L, DemandQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 0L, 0);
        sendSystemMessagePurchaseInquiry(purchaseInquiry, MessageTemplateCode.demand_quotation_wait_audit);
        return Wrapper.success();
    }

    /**
     * 解密报价单
     */
    @Override
    public Wrapper decryptQuotedPrice(DecryptQuotedPriceRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        List<QuotedPrice> quotedPrices = quotedPriceRepository.findAllByPurchaseInquiryId(purchaseInquiry.getId());
        if (CollectionUtils.isEmpty(quotedPrices)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        //判断秘钥是否正确
        CheckPasswordDTO checkPasswordRequest = new CheckPasswordDTO();
        checkPasswordRequest.setMemberId(sysUser.getMemberId());
        checkPasswordRequest.setMemberRoleId(sysUser.getMemberRoleId());
        checkPasswordRequest.setPassword(request.getPassword());
        Wrapper<Boolean> booleanWrapper = secretKeyControllerFeign.checkPassword(checkPasswordRequest);
        if (ResponseCode.SUCCESS.getCode() != booleanWrapper.getCode()) {
            return booleanWrapper;
        }
        quotedPrices.forEach(quotedPrice -> {
            quotedPrice.setIsDecrypt(OrderConstant.State.START);
        });
        quotedPriceRepository.saveAll(quotedPrices);
        return Wrapper.success();
    }

    /**
     * 提交比价
     */
    @Transactional
    @Override
    public Wrapper submitContrastPrice(SubmitContrastPriceRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        List<QuotedPrice> quotedPrices = quotedPriceRepository.findAllByPurchaseInquiryId(purchaseInquiry.getId());
        if (CollectionUtils.isEmpty(quotedPrices)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        purchaseInquiry.setUrls(request.getUrls());
        purchaseInquiry.setAwardComments(request.getAwardComments());
        List<PriceParityDetailsResponse> priceParityInfos = request.getPriceParityInfos();
        List<AwardInfoResponse> list = new ArrayList<>();
        //保存比价信息
        priceParityInfos.forEach(details -> {
            list.addAll(details.getAwardInfoResponses());
        });
        //保存授标金额和状态
        setSumImkPrice(priceParityInfos, quotedPrices);
        Map<Long, AwardInfoResponse> collect = list.stream().collect(Collectors.toMap(AwardInfoResponse::getId, awardInfo -> awardInfo));
        List<QuotedPriceDetails> quotedPriceDetailss = quotedPriceDetailsRepository.findAllById(collect.keySet());
        if (CollectionUtils.isEmpty(quotedPriceDetailss)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        quotedPriceDetailss.forEach(quotedPriceDetails -> {
            AwardInfoResponse awardInfoResponse = collect.get(quotedPriceDetails.getId());
            quotedPriceDetails.setIsPrize(awardInfoResponse.getIsPrize());
            quotedPriceDetails.setAwardTaxProbability(awardInfoResponse.getAwardTaxProbability());
        });
        quotedPriceDetailsRepository.saveAll(quotedPriceDetailss);
        //执行内部工作流
        Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), purchaseInquiry.getId(), ProcessEnum.PURCHASE_CONFIRM_OFFER_INNER_VERIFY.getCode(), purchaseInquiry.getConfirmInteriorNextStep(), purchaseInquiry.getConfirmInteriorTaskId(), OrderConstant.Auditing.DEFAULT);
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            return taskResult;
        }
        SimpleTaskCompleteVO data = taskResult.getData();
        purchaseInquiry.setConfirmInteriorState(data.getStatus());
        purchaseInquiry.setConfirmInteriorNextStep(data.getStatus());
        purchaseInquiry.setConfirmInteriorTaskId(data.getTaskId());
        purchaseInquiry.setUpdateTime(System.currentTimeMillis());
        purchaseInquiryRepository.saveAndFlush(purchaseInquiry);
        quotedPriceRepository.saveAll(quotedPrices);
        reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_DEMAND_QUOTATION.getCode(), 1L, ConfirmDemandQuotationOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode(), 1L, ConfirmDemandQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode());
        sendSystemMessagePurchaseInquiry(purchaseInquiry, MessageTemplateCode.confirm_demand_quotation_audit_step_1);
        //保存操作日志
        saveInteriorLog(sysUser, PurchaseInquiryListInteriorWorkStateEnum.STAY_EXAMINE_AWARD_RESULTS1.getName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), purchaseInquiry.getId(), "");
        return Wrapper.success();
    }

    /**
     * 待审核授标结果(一级)
     */
    @Override
    public Wrapper<PageData<PurchaseInquiryListResponse>> stayExamineAward1List(PurchaseInquiryListRequest request, UserLoginCacheDTO sysUser) {
        return getPurchaseInquiryList(sysUser, request, ConfirmQuotedPriceQueryEnum.STAY_EXAMINE_AWARD_RESULTS1.getType());
    }

    /**
     * 审核授标结果(一级)
     */
    @Override
    public Wrapper stayExamineAward1(BaseExamineRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        //执行内部工作流
        Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), purchaseInquiry.getId(), ProcessEnum.PURCHASE_CONFIRM_OFFER_INNER_VERIFY.getCode(), purchaseInquiry.getConfirmInteriorNextStep(), purchaseInquiry.getConfirmInteriorTaskId(), request.getState());
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            return taskResult;
        }
        SimpleTaskCompleteVO data = taskResult.getData();
        purchaseInquiry.setConfirmInteriorState(data.getStatus());
        purchaseInquiry.setConfirmInteriorNextStep(data.getStatus());
        purchaseInquiry.setConfirmInteriorTaskId(data.getTaskId());
        purchaseInquiry.setUpdateTime(System.currentTimeMillis());
        purchaseInquiryRepository.saveAndFlush(purchaseInquiry);
        //是否审核通过
        boolean isAuditing = OrderConstant.Auditing.PASS == request.getState();
        if (isAuditing) {
            saveInteriorLog(sysUser, PurchaseInquiryListInteriorWorkStateEnum.STAY_EXAMINE_AWARD_RESULTS2.getName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), purchaseInquiry.getId(), StatusEnum.AGREE.getCHName());
        } else {
            saveInteriorLog(sysUser, PurchaseInquiryListInteriorWorkStateEnum.EXAMINE_AWARD_RESULTS1.getName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), purchaseInquiry.getId(), request.getAuditOpinion());

        }
        reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_DEMAND_QUOTATION.getCode(), 1L, isAuditing ? ConfirmDemandQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode() : ConfirmDemandQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 1L, ConfirmDemandQuotationOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode());
        sendSystemMessagePurchaseInquiry(purchaseInquiry, isAuditing ? MessageTemplateCode.confirm_demand_quotation_audit_step_2 : MessageTemplateCode.confirm_demand_quotation_wait_audit);
        return Wrapper.success();
    }

    /**
     * 审核授标结果(一级)
     */
    @Override
    public Wrapper stayExamineAwards1(BaseAllRequest request, UserLoginCacheDTO sysUser) {
        for (Long id : request.getIds()) {
            PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(id, sysUser.getMemberId(), sysUser.getMemberRoleId());
            if (ObjectUtils.isEmpty(purchaseInquiry)) {
                return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
            }
            //执行内部工作流
            Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), purchaseInquiry.getId(), ProcessEnum.PURCHASE_CONFIRM_OFFER_INNER_VERIFY.getCode(), purchaseInquiry.getConfirmInteriorNextStep(), purchaseInquiry.getConfirmInteriorTaskId(), OrderConstant.Auditing.PASS);
            if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
                return taskResult;
            }
            SimpleTaskCompleteVO data = taskResult.getData();
            purchaseInquiry.setConfirmInteriorState(data.getStatus());
            purchaseInquiry.setConfirmInteriorNextStep(data.getStatus());
            purchaseInquiry.setConfirmInteriorTaskId(data.getTaskId());
            purchaseInquiry.setUpdateTime(System.currentTimeMillis());
            purchaseInquiryRepository.saveAndFlush(purchaseInquiry);
            saveInteriorLog(sysUser, PurchaseInquiryListInteriorWorkStateEnum.STAY_EXAMINE_AWARD_RESULTS2.getName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), purchaseInquiry.getId(), "同意");
            reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_DEMAND_QUOTATION.getCode(), 1L, ConfirmDemandQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode(), 1L, ConfirmDemandQuotationOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode());
            sendSystemMessagePurchaseInquiry(purchaseInquiry, MessageTemplateCode.confirm_demand_quotation_audit_step_2);
        }
        return Wrapper.success();
    }

    /**
     * 待审核授标结果(二级)
     */
    @Override
    public Wrapper<PageData<PurchaseInquiryListResponse>> stayExamineAward2List(PurchaseInquiryListRequest request, UserLoginCacheDTO sysUser) {
        return getPurchaseInquiryList(sysUser, request, ConfirmQuotedPriceQueryEnum.STAY_EXAMINE_AWARD_RESULTS2.getType());
    }

    /**
     * 审核授标结果(二级)
     */
    @Override
    public Wrapper stayExamineAward2(BaseExamineRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        //执行内部工作流
        Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), purchaseInquiry.getId(), ProcessEnum.PURCHASE_CONFIRM_OFFER_INNER_VERIFY.getCode(), purchaseInquiry.getConfirmInteriorNextStep(), purchaseInquiry.getConfirmInteriorTaskId(), request.getState());
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            return taskResult;
        }
        SimpleTaskCompleteVO data = taskResult.getData();
        purchaseInquiry.setConfirmInteriorState(data.getStatus());
        purchaseInquiry.setConfirmInteriorNextStep(data.getStatus());
        purchaseInquiry.setConfirmInteriorTaskId(data.getTaskId());
        purchaseInquiry.setUpdateTime(System.currentTimeMillis());
        purchaseInquiryRepository.saveAndFlush(purchaseInquiry);
        //是否审核通过
        boolean isAuditing = OrderConstant.Auditing.PASS == request.getState();
        if (isAuditing) {
            saveInteriorLog(sysUser, PurchaseInquiryListInteriorWorkStateEnum.STAY_CONFIRM_AWARD_RESULTS.getName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), purchaseInquiry.getId(), StatusEnum.AGREE.getName());
        } else {
            saveInteriorLog(sysUser, PurchaseInquiryListInteriorWorkStateEnum.EXAMINE_AWARD_RESULTS2.getName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), purchaseInquiry.getId(), request.getAuditOpinion());
        }
        reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_DEMAND_QUOTATION.getCode(), 1L, isAuditing ? ConfirmDemandQuotationOperateTypeEnum.TO_BE_CONFIRM.getCode() : ConfirmDemandQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 1L, ConfirmDemandQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode());
        sendSystemMessagePurchaseInquiry(purchaseInquiry, isAuditing ? MessageTemplateCode.confirm_demand_quotation_confirm : MessageTemplateCode.confirm_demand_quotation_wait_audit);
        return Wrapper.success();
    }

    /**
     * 批量审核授标结果(二级)
     */
    @Override
    public Wrapper stayExamineAwards2(BaseAllRequest request, UserLoginCacheDTO sysUser) {
        for (Long id : request.getIds()) {
            PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(id, sysUser.getMemberId(), sysUser.getMemberRoleId());
            if (ObjectUtils.isEmpty(purchaseInquiry)) {
                return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
            }
            //执行内部工作流
            Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), purchaseInquiry.getId(), ProcessEnum.PURCHASE_CONFIRM_OFFER_INNER_VERIFY.getCode(), purchaseInquiry.getConfirmInteriorNextStep(), purchaseInquiry.getConfirmInteriorTaskId(), OrderConstant.Auditing.PASS);
            if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
                return taskResult;
            }
            SimpleTaskCompleteVO data = taskResult.getData();
            purchaseInquiry.setConfirmInteriorState(data.getStatus());
            purchaseInquiry.setConfirmInteriorNextStep(data.getStatus());
            purchaseInquiry.setConfirmInteriorTaskId(data.getTaskId());
            purchaseInquiry.setUpdateTime(System.currentTimeMillis());
            purchaseInquiryRepository.saveAndFlush(purchaseInquiry);
            //是否审核通过
            saveInteriorLog(sysUser, PurchaseInquiryListInteriorWorkStateEnum.STAY_CONFIRM_AWARD_RESULTS.getName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), purchaseInquiry.getId(), StatusEnum.AGREE.getName());
            reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_DEMAND_QUOTATION.getCode(), 1L, ConfirmDemandQuotationOperateTypeEnum.TO_BE_CONFIRM.getCode(), 1L, ConfirmDemandQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode());
            sendSystemMessagePurchaseInquiry(purchaseInquiry, MessageTemplateCode.confirm_demand_quotation_confirm);
        }
        return Wrapper.success();
    }

    /**
     * 待确认授标结果
     */
    @Override
    public Wrapper<PageData<PurchaseInquiryListResponse>> stayConfirmAwardResultList(PurchaseInquiryListRequest request, UserLoginCacheDTO sysUser) {
        return getPurchaseInquiryList(sysUser, request, ConfirmQuotedPriceQueryEnum.STAY_CONFIRM_AWARD_RESULTS.getType());
    }

    /**
     * 确认授标结果
     */
    @Override
    public Wrapper stayConfirmAwardResult(BaseExamineRequest request, UserLoginCacheDTO sysUser) {
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        List<QuotedPrice> quotedPrices = quotedPriceRepository.findAllByPurchaseInquiryId(purchaseInquiry.getId());
        if (CollectionUtils.isEmpty(quotedPrices)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        //执行内部工作流
        Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), purchaseInquiry.getId(), ProcessEnum.PURCHASE_CONFIRM_OFFER_INNER_VERIFY.getCode(), purchaseInquiry.getConfirmInteriorNextStep(), purchaseInquiry.getConfirmInteriorTaskId(), OrderConstant.Auditing.DEFAULT);
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            return taskResult;
        }
        SimpleTaskCompleteVO data = taskResult.getData();
        purchaseInquiry.setConfirmInteriorState(data.getStatus());
        purchaseInquiry.setConfirmInteriorNextStep(data.getStatus());
        purchaseInquiry.setConfirmInteriorTaskId(data.getTaskId());
        purchaseInquiry.setUpdateTime(System.currentTimeMillis());
        //执行外部工作流
        Wrapper<SimpleTaskCompleteVO> executeResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), purchaseInquiry.getId(), ProcessEnum.PURCHASE_INQUIRY_OUTER_VERIFY.getCode(), purchaseInquiry.getExternalNextStep(), purchaseInquiry.getExternalTaskId(), OrderConstant.Auditing.PASS);
        if (ResponseCode.SUCCESS.getCode() != executeResult.getCode()) {
            return executeResult;
        }
        purchaseInquiry.setExternalTaskId(executeResult.getData().getTaskId());
        purchaseInquiry.setExternalState(executeResult.getData().getStatus());
        purchaseInquiry.setExternalNextStep(executeResult.getData().getStep());
        purchaseInquiry.setNotice(request.getNotice());
        purchaseInquiry.setThank(request.getThank());
        purchaseInquiry.setPrizeNotice(request.getPrizeNotice());
        purchaseInquiry.setContent(request.getContent());
        purchaseInquiry.setAwardResults(request.getAwardResults());
        List<QuotedPriceDetails> quotedPriceDetailss = quotedPriceDetailsRepository.findAllByTurnAndQuotedPriceIdIn(purchaseInquiry.getTurn(), quotedPrices.stream().map(QuotedPrice::getId).collect(Collectors.toList()), Sort.by("id").ascending());
        //按报价单分组
        Map<Long, List<QuotedPriceDetails>> quotedPriceDetailsgroupingBy = quotedPriceDetailss.stream().collect(Collectors.groupingBy(QuotedPriceDetails::getQuotedPriceId));
        Map<Long, Integer> isPrizeMap = getIsPrize(quotedPriceDetailsgroupingBy);
        if (!CollectionUtils.isEmpty(quotedPrices)) {
            quotedPrices.forEach(quotedPrice -> {
                quotedPrice.setExternalTaskId(executeResult.getData().getTaskId());
                quotedPrice.setExternalState(executeResult.getData().getStatus());
                quotedPrice.setExternalNextStep(executeResult.getData().getStep());
                Integer isPrize = isPrizeMap.get(quotedPrice.getId());
                quotedPrice.setIsPrize(isPrize == null ? OrderConstant.State.STOP : isPrize);
                quotedPrice.setUpdateTime(System.currentTimeMillis());
                quotedPrice.setNotice(request.getNotice());
                quotedPrice.setThank(request.getThank());
                quotedPrice.setPrizeNotice(request.getPrizeNotice());

                //发送感谢函 勾选了发送感谢函并且未中标的商家
                if (OrderConstant.State.START.equals(request.getThank()) && OrderConstant.State.STOP.equals(quotedPrice.getIsPrize())) {
                    quotedPrice.setContent(request.getContent());
                    sendSystemMessagePurchaseInquiryCustom(quotedPrice, MessageTitle.confirm_demand_quotation, request.getContent());
                }
                //发送中标通知 勾选了发送中标同并且中标的商家
                if (OrderConstant.State.START.equals(request.getPrizeNotice()) && OrderConstant.State.START.equals(quotedPrice.getIsPrize())) {
                    quotedPrice.setAwardResults(request.getAwardResults());
                    sendSystemMessagePurchaseInquiryCustom(quotedPrice, MessageTitle.confirm_demand_quotation, request.getAwardResults());
                }
            });
            quotedPriceRepository.saveAll(quotedPrices);
        }
        purchaseInquiryRepository.saveAndFlush(purchaseInquiry);
        saveInteriorLog(sysUser, PurchaseInquiryListInteriorWorkStateEnum.COMPLETE.getName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), purchaseInquiry.getId(), "");
        reduceCount(purchaseInquiry.getDetails(), purchaseInquiry.getCreateMemberId(), purchaseInquiry.getCreateMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_DEMAND_QUOTATION.getCode(), 0L, 0, 1L, ConfirmDemandQuotationOperateTypeEnum.TO_BE_CONFIRM.getCode());
        //同步中标信息给采购合同服务 只同步已经授标的单据
        List<PurchaseInquiryAddVO> collect = quotedPrices.stream().filter(quotedPrice -> OrderConstant.State.START.equals(quotedPrice.getIsPrize())).map(temp -> {
            PurchaseInquiryAddVO vo = new PurchaseInquiryAddVO();
            vo.setTurn(temp.getTurn());
            vo.setPurchaseType(purchaseInquiry.getPurchaseType());
            vo.setAwardAmount(temp.getSumImMark());
            vo.setOuterStatus(temp.getExternalState());
            vo.setInnerStatus(temp.getInteriorState());
            vo.setDemandRoleId(purchaseInquiry.getCreateMemberRoleId());
            vo.setDemandMemberId(purchaseInquiry.getCreateMemberId());
            vo.setDemandPublishTime(purchaseInquiry.getCreateTime());
            vo.setDemandNO(purchaseInquiry.getPurchaseInquiryNo());
            vo.setDemandId(purchaseInquiry.getId());
            vo.setDemandAbstract(purchaseInquiry.getDetails());
            vo.setAwardTime(temp.getUpdateTime());
            vo.setAwardRoleId(temp.getCreateMemberRoleId());
            vo.setAwardName(temp.getCreateMemberName());
            vo.setAwardMemberId(temp.getCreateMemberId());
            vo.setId(temp.getId());
            vo.setOrderNo(temp.getQuotedPriceNo());
            return vo;
        }).collect(Collectors.toList());
        purchaseInquiryControllerFeign.addList(collect);

        //中标公示(企业门户用到)
        if (OrderConstant.State.START.equals(request.getNotice())) {
            PurchaseNotice purchaseNotice = new PurchaseNotice();
            purchaseNotice.setMemberId(sysUser.getMemberId());
            purchaseNotice.setRoleId(sysUser.getMemberRoleId());
            purchaseNotice.setType(PurchaseNoticeTypeEnum.ENQUIRY.getCode());
            purchaseNotice.setName(purchaseInquiry.getDetails());
            purchaseNotice.setCreateTime(System.currentTimeMillis());
            purchaseNotice.setContent(request.getAwardResults());
            purchaseNotice.setMemberIds(
                    quotedPrices.stream().filter(a ->
                            EnableDisableStatus.ENABLE.getCode().equals(a.getIsPrize())
                    ).map(QuotedPrice::getCreateMemberId).collect(Collectors.toList())
            );
            purchaseNotice.setDataId(purchaseInquiry.getId());
            purchaseNotice.setShopIds(purchaseInquiry.getShopIds());
            purchaseNoticeRepository.saveAndFlush(purchaseNotice);
        }

        return Wrapper.success();
    }

    /**
     * 报价供应商信息
     */
    @Override
    public Wrapper<PageData<QuotedPriceInfoResponse>> quotedPriceInfoList(QuotedPriceInfoRequest request, UserLoginCacheDTO sysUser) {
        //根据需求单获取报价单轮次
        List<QuotedPriceTurn> turns = quotedPriceTurnRepository.findByPurchaseInquiryIdAndTurnAndStatus(
                request.getId(), request.getTurn(), EnableDisableStatus.ENABLE.getCode()
        );
        if (CollectionUtils.isEmpty(turns)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        //根据轮次的报价单ID获取报价单
        List<QuotedPrice> quotedPrices = quotedPriceRepository.findAllById(
                turns.stream().map(QuotedPriceTurn::getQuotedPriceId).collect(Collectors.toList())
        );

        if (CollectionUtils.isEmpty(quotedPrices)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }
        Map<Long, QuotedPrice> quotedPriceMap = quotedPrices.stream().collect(Collectors.toMap(QuotedPrice::getId, quotedPrice -> quotedPrice));
        //查询本轮次的报价详情
        List<QuotedPriceDetails> quotedPriceDetailss = quotedPriceDetailsRepository.findAllByTurnAndQuotedPriceIdIn(request.getTurn(), new ArrayList<>(quotedPriceMap.keySet()), Sort.by("id").ascending());
        if (CollectionUtils.isEmpty(quotedPriceDetailss)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }
        Map<Long, List<QuotedPriceDetails>> quotedPriceDetailsMap = quotedPriceDetailss.stream().collect(Collectors.groupingBy(QuotedPriceDetails::getQuotedPriceId));
        Set<Long> longs = quotedPriceDetailsMap.keySet();
        List<QuotedPriceInfoResponse> collect = longs.stream().map(temp -> {
            QuotedPriceInfoResponse response = new QuotedPriceInfoResponse();
            QuotedPrice quotedPrice = quotedPriceMap.get(temp);
            BeanUtils.copyProperties(quotedPrice, response);
            response.setSumImMark(quotedPrice.getSumImMark());

            List<QuotedPriceDetails> quotedPriceDetails = quotedPriceDetailsMap.get(temp);
            if (CollectionUtil.isNotEmpty(quotedPriceDetails)) {
                response.setSumPrice(quotedPriceDetails.stream().mapToDouble(QuotedPriceDetails::getTaxPrice).sum());
            }

            QuotedPriceTurn quotedPriceTurn = turns.stream().filter(a -> a.getQuotedPriceId().equals(quotedPrice.getId())).findFirst().orElse(null);
            if (quotedPriceTurn != null) {
                response.setContacts(quotedPriceTurn.getContacts());
                response.setTel(quotedPriceTurn.getTel());
                response.setQuotedDetails(quotedPriceTurn.getQuotedDetails());
                response.setCreateTime(quotedPriceTurn.getTradeTime());
            }

            return response;
        }).collect(Collectors.toList());
        collect = CollectionPageUtil.pageList(collect, request.getCurrent(), request.getPageSize());

        return Wrapper.success(new PageData<>((long) longs.size(), collect));
    }

    /**
     * 采购确认报价单工作流内部状态枚举
     */
    @Override
    public Wrapper<List<BiddingExternalWorkStateEnumResponse>> interiorStatus() {
        List<BiddingExternalWorkStateEnumResponse> collect = Arrays.stream(PurchaseInquiryListInteriorWorkStateEnum.values()).map(temp -> {
            BiddingExternalWorkStateEnumResponse response = new BiddingExternalWorkStateEnumResponse();
            response.setName(temp.getName());
            response.setSatatus(temp.getState());
            return response;
        }).collect(Collectors.toList());
        return Wrapper.success(collect);
    }


    /**
     * 根据不同类型查询采购询价单列表 queryType：
     */
    private Wrapper<PageData<PurchaseInquiryListResponse>> getPurchaseInquiryList(UserLoginCacheDTO sysUser, PurchaseInquiryListRequest request, Integer queryType) {
        List<PurchaseInquiryListResponse> responses = new ArrayList<>();
        Specification<PurchaseInquiry> purchaseInquiryQuery = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(criteriaBuilder.equal(root.get("createMemberId").as(Long.class), sysUser.getMemberId()));
            predicates.add(criteriaBuilder.equal(root.get("createMemberRoleId").as(Long.class), sysUser.getMemberRoleId()));
            queryCondition(request.getMemberName(), request.getStartTime(), request.getEndTime(), request.getDetails(), request.getPurchaseInquiryNo(), predicates, criteriaBuilder, root);
            if (ConfirmQuotedPriceQueryEnum.QUOTATION_INQUIRY.getType().equals(queryType)) {
                predicates.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("externalState"), PurchaseInquiryListExternalWorkStateEnum.STAY_SUBMIT_OFFER.getState()),
                        criteriaBuilder.equal(root.get("externalState"), PurchaseInquiryListExternalWorkStateEnum.STAY_CONFIRMATION_OF_AWARD.getState()),
                        criteriaBuilder.equal(root.get("externalState"), PurchaseInquiryListExternalWorkStateEnum.LAUNCH_NEXT_TURN.getState()),
                        criteriaBuilder.equal(root.get("externalState"), PurchaseInquiryListExternalWorkStateEnum.COMPLETE.getState())));
                if (null != request.getExternalState()) {
                    predicates.add(criteriaBuilder.equal(root.get("externalState"), request.getExternalState()));
                }
                if (null != request.getInteriorState()) {
                    predicates.add(criteriaBuilder.equal(root.get("interiorState"), request.getInteriorState()));
                }
            } else if (ConfirmQuotedPriceQueryEnum.STAY_PRICE_PARITY.getType().equals(queryType)) {
                predicates.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("confirmInteriorState"), PurchaseInquiryListInteriorWorkStateEnum.STAY_CONTRAST_PRICE.getState()),
                        criteriaBuilder.equal(root.get("confirmInteriorState"), PurchaseInquiryListInteriorWorkStateEnum.EXAMINE_AWARD_RESULTS1.getState()),
                        criteriaBuilder.equal(root.get("confirmInteriorState"), PurchaseInquiryListInteriorWorkStateEnum.EXAMINE_AWARD_RESULTS2.getState())));
                predicates.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("externalState"), PurchaseInquiryListExternalWorkStateEnum.STAY_CONFIRMATION_OF_AWARD.getState())));
            } else if (ConfirmQuotedPriceQueryEnum.STAY_EXAMINE_AWARD_RESULTS1.getType().equals(queryType)) {
                predicates.add(criteriaBuilder.equal(root.get("confirmInteriorState"), PurchaseInquiryListInteriorWorkStateEnum.STAY_EXAMINE_AWARD_RESULTS1.getState()));
                predicates.add(criteriaBuilder.equal(root.get("externalState"), PurchaseInquiryListExternalWorkStateEnum.STAY_CONFIRMATION_OF_AWARD.getState()));
            } else if (ConfirmQuotedPriceQueryEnum.STAY_EXAMINE_AWARD_RESULTS2.getType().equals(queryType)) {
                predicates.add(criteriaBuilder.equal(root.get("confirmInteriorState"), PurchaseInquiryListInteriorWorkStateEnum.STAY_EXAMINE_AWARD_RESULTS2.getState()));
                predicates.add(criteriaBuilder.equal(root.get("externalState"), PurchaseInquiryListExternalWorkStateEnum.STAY_CONFIRMATION_OF_AWARD.getState()));
            } else if (ConfirmQuotedPriceQueryEnum.STAY_CONFIRM_AWARD_RESULTS.getType().equals(queryType)) {
                predicates.add(criteriaBuilder.equal(root.get("confirmInteriorState"), PurchaseInquiryListInteriorWorkStateEnum.STAY_CONFIRM_AWARD_RESULTS.getState()));
                predicates.add(criteriaBuilder.equal(root.get("externalState"), PurchaseInquiryListExternalWorkStateEnum.STAY_CONFIRMATION_OF_AWARD.getState()));
            }
            Predicate[] predicate = new Predicate[predicates.size()];
            return criteriaBuilder.and(predicates.toArray(predicate));
        };
        Page<PurchaseInquiry> purchaseInquirys = purchaseInquiryRepository.findAll(purchaseInquiryQuery, PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("createTime").descending()));
        if (0 < purchaseInquirys.getTotalElements()) {
            responses = purchaseInquirys.getContent().stream().map(temp -> {
                PurchaseInquiryListResponse response = new PurchaseInquiryListResponse();
                response.setCreateTime(temp.getCreateTime());
                response.setDeliveryTime(temp.getDeliveryTime());
                response.setPurchaseInquiryNo(temp.getPurchaseInquiryNo());
                response.setOfferEndTime(temp.getOfferEndTime());
                response.setId(temp.getId());
                response.setMemberRoleId(temp.getMemberRoleId());
                response.setMemberName(temp.getMemberName());
                response.setMemberId(temp.getMemberId());
                response.setInteriorStateName(PurchaseInquiryListExternalWorkStateEnum.STAY_SUBMIT_OFFER.getState().equals(temp.getExternalState()) ? PurchaseInquiryListInteriorWorkStateEnum.getName(temp.getInteriorState()) : "");
                response.setInteriorState(temp.getInteriorState());
                response.setExternalStateName(PurchaseInquiryListExternalWorkStateEnum.getName(temp.getExternalState()));
                response.setExternalState(temp.getExternalState());
                response.setConfirmInteriorState(temp.getConfirmInteriorState());
                response.setConfirmInteriorNextStep(temp.getConfirmInteriorNextStep());
                response.setConfirmInteriorStateName(PurchaseInquiryListInteriorWorkStateEnum.getName(temp.getConfirmInteriorState()));
                response.setDetails(temp.getDetails());
                response.setCreateTime(temp.getCreateTime());
                response.setCount(temp.getCount());
                response.setTurn(temp.getTurn());
                return response;
            }).collect(Collectors.toList());
        }
        return Wrapper.success(new PageData<>(purchaseInquirys.getTotalElements(), responses));
    }


    /**
     * 统计报价单比价信息
     */
    private List<PriceParityDetailsResponse> info(List<QuotedPrice> quotedPrices, List<QuotedPriceDetails> quotedPriceDetailss) {
        List<PriceParityDetailsResponse> list = new ArrayList<>();
        Map<Long, List<QuotedPriceDetails>> quotedPriceDetailsMap = quotedPriceDetailss.stream().collect(Collectors.groupingBy(QuotedPriceDetails::getQuotedPriceId));
        for (QuotedPrice quotedPrice : quotedPrices) {
            PriceParityDetailsResponse memberQuotedPrice = new PriceParityDetailsResponse();
            List<QuotedPriceDetails> detailss = quotedPriceDetailsMap.get(quotedPrice.getId());
            List<AwardInfoResponse> awardInfoResponses = detailss.stream().map(temp -> {
                //查询对应的物料报价信息
                AwardInfoResponse awardInfoResponse = new AwardInfoResponse();
                awardInfoResponse.setId(temp.getId());
                awardInfoResponse.setGoodsId(temp.getGoodsId());
                awardInfoResponse.setTaxUnitPrice(temp.getTaxUnitPrice());
                awardInfoResponse.setIsTax(temp.getIsTax());
                awardInfoResponse.setIsPrize(temp.getIsPrize());
                awardInfoResponse.setTaxPrice(temp.getTaxPrice());
                awardInfoResponse.setTaxProbability(temp.getTaxProbability());
                awardInfoResponse.setAwardTaxProbability(temp.getAwardTaxProbability());
                awardInfoResponse.setUnit(temp.getUnit());
                awardInfoResponse.setBrand(temp.getBrand());
                awardInfoResponse.setCategory(temp.getCategory());
                awardInfoResponse.setGoodsId(temp.getGoodsId());
                awardInfoResponse.setNumber(temp.getNumber());
                awardInfoResponse.setModel(temp.getModel());
                awardInfoResponse.setName(temp.getName());
                awardInfoResponse.setPurchaseCount(temp.getPurchaseCount());
                return awardInfoResponse;
            }).collect(Collectors.toList());
            memberQuotedPrice.setAwardInfoResponses(awardInfoResponses);
            memberQuotedPrice.setId(quotedPrice.getId());
            memberQuotedPrice.setSubtotal(detailss.stream().mapToDouble(QuotedPriceDetails::getTaxPrice).sum());
            memberQuotedPrice.setSumPrice(sumPrice(detailss));
            memberQuotedPrice.setMemberId(quotedPrice.getCreateMemberId());
            memberQuotedPrice.setMemberRoleId(quotedPrice.getCreateMemberRoleId());
            memberQuotedPrice.setMemberName(quotedPrice.getCreateMemberName());
            memberQuotedPrice.setAwardCount((int) detailss.stream().filter(v -> OrderConstant.State.START.equals(v.getIsPrize())).count());
            list.add(memberQuotedPrice);
        }
        //报价排名
        ranking(list);
        //最低价授标数量
        return statistic(quotedPriceDetailss, list);
    }

    /**
     * 计算授标含税总额
     */
    private Double sumPrice(List<QuotedPriceDetails> quotedPriceDetailss) {
        double sumPrice = 0D;
        for (QuotedPriceDetails quotedPriceDetails : quotedPriceDetailss) {
            if (OrderConstant.State.START.equals(quotedPriceDetails.getIsPrize())) {
                //计算单个物料授标金额
                sumPrice += quotedPriceDetails.getTaxPrice() * quotedPriceDetails.getAwardTaxProbability() / 100;
            }
        }
        return BigDecimal.valueOf(sumPrice).setScale(2, RoundingMode.HALF_UP).doubleValue();
    }

    /**
     * 计算报价排名
     */
    private void ranking(List<PriceParityDetailsResponse> list) {
        list = list.stream().sorted(Comparator.comparing(PriceParityDetailsResponse::getSubtotal)).collect(Collectors.toList());
        for (int i = 0; i < list.size(); i++) {
            int j = i;
            list.get(i).setRanking(j + 1);
        }
        // list.stream().sorted(Comparator.comparing(PriceParityDetailsResponse::getRanking)).collect(Collectors.toList());
    }

    /**
     * 统计用户最低价授标数量
     */
    private List<PriceParityDetailsResponse> statistic(List<QuotedPriceDetails> quotedPriceDetailss, List<PriceParityDetailsResponse> list) {
        Map<Long, Integer> map = new HashMap<>();
        Map<Long, List<QuotedPriceDetails>> groupingByGoodsId = quotedPriceDetailss.stream().collect(Collectors.groupingBy(QuotedPriceDetails::getGoodsId));
        groupingByGoodsId.keySet().forEach(id -> {
            List<QuotedPriceDetails> detailss = groupingByGoodsId.get(id).stream().sorted(Comparator.comparing(QuotedPriceDetails::getTaxUnitPrice)).collect(Collectors.toList());
            QuotedPriceDetails quotedPriceDetails = detailss.get(0);
            map.merge(quotedPriceDetails.getQuotedPriceId(), 1, Integer::sum);
        });
        list.forEach(temp -> {
            temp.setMinimum(map.get(temp.getId()));
        });
        //按照排名排序
        return list.stream().sorted(Comparator.comparing(PriceParityDetailsResponse::getRanking)).collect(Collectors.toList());
    }

    /**
     * 统计报价单是否中标
     */
    private Map<Long, Integer> getIsPrize(Map<Long, List<QuotedPriceDetails>> collect) {
        Map<Long, Integer> map = new HashMap<>();
        collect.keySet().forEach(id -> {
            List<QuotedPriceDetails> quotedPriceDetails = collect.get(id);
            Boolean aBoolean = isPrize(quotedPriceDetails);
            map.put(id, aBoolean ? OrderConstant.State.START : OrderConstant.State.STOP);
        });
        return map;
    }

    /**
     * 判断报价单是否中标
     */
    private Boolean isPrize(List<QuotedPriceDetails> quotedPriceDetails) {
        for (QuotedPriceDetails details : quotedPriceDetails) {
            Integer isPrize = details.getIsPrize();
            if (OrderConstant.State.START.equals(isPrize)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 记录采购询价单内部操作记录
     */
    private void saveInteriorLog(UserLoginCacheDTO sysUser, String operation, Integer step, Integer state, Long id, String auditOpinion) {
        //记录操作记录
        InteriorConfirmQuotedPriceLog interiorLog = new InteriorConfirmQuotedPriceLog();
        interiorLog.setRoleName(sysUser.getUserName());
        interiorLog.setDepartment(sysUser.getUserOrgName());
        interiorLog.setPosition(sysUser.getUserJobTitle());
        interiorLog.setPurchaseInquiryId(id);
        interiorLog.setState(state);
        interiorLog.setStep(step);
        interiorLog.setOperation(operation);
        interiorLog.setAuditOpinion(auditOpinion);
        interiorLog.setCreateTime(System.currentTimeMillis());
        interiorLog.setCreateRoleId(sysUser.getMemberRoleId());
        interiorLog.setCreateMemberId(sysUser.getMemberId());
        interiorConfirmQuotedPriceLogRepository.saveAndFlush(interiorLog);
    }

    /**
     * 生成中标通知
     */
    private String generateAwardResult(PurchaseInquiry purchaseInquiry, Integer isPrize) {
        if (OrderConstant.State.STOP.equals(isPrize)) {
            return "贵公司参与了我公司《" + purchaseInquiry.getDetails() + "》竞标。在我公司综合各投标单位的基本情况，并进行充分技术交流后，经评标委员会综合评定，贵公司未能中标。我公司对贵公司的积极参与和支持深表感谢!希望下次合作成功。";
        }
        List<QuotedPrice> quotedPrices = quotedPriceRepository.findAllByPurchaseInquiryId(purchaseInquiry.getId());
        List<QuotedPriceDetails> quotedPriceDetailss = quotedPriceDetailsRepository.findAllByTurnAndQuotedPriceIdIn(purchaseInquiry.getTurn(), quotedPrices.stream().map(QuotedPrice::getId).collect(Collectors.toList()), Sort.by("taxUnitPrice").ascending());
        Map<Long, List<QuotedPriceDetails>> collect = quotedPriceDetailss.stream().collect(Collectors.groupingBy(QuotedPriceDetails::getQuotedPriceId));
        String award = purchaseInquiry.getCreateMemberName() + "《" + purchaseInquiry.getDetails() + "》评标工作评标工作已经结束，中标人已经确定。现将中标结果公布如下：中标供应商：";
        for (QuotedPrice details : quotedPrices) {
            Double sumPrice = sumPrice(collect.get(details.getId()));
            details.setSumImMark(sumPrice);
            if (OrderConstant.State.START.equals(details.getIsPrize()) && sumPrice > 0) {
                award = details.getMemberName() + "（中标总金额（含税）：" + sumPrice + "），";
            }
        }
        award += "中标理由：价格最低";
        return award;
    }


    /**
     * 设置报价单中标总金额 和中标数量
     */
    private void setSumImkPrice(List<PriceParityDetailsResponse> priceParityInfos, List<QuotedPrice> quotedPrices) {
        if (CollectionUtils.isEmpty(priceParityInfos) || CollectionUtils.isEmpty(quotedPrices)) {
            return;
        }
        Map<Long, PriceParityDetailsResponse> collect = priceParityInfos.stream().collect(Collectors.toMap(PriceParityDetailsResponse::getId, priceParityDetails -> priceParityDetails));
        Map<Long, Double> longDoubleMap = countSumImkPrice(priceParityInfos);
        quotedPrices.forEach(quotedPrice -> {
            Double aDouble = longDoubleMap.get(quotedPrice.getId());
            quotedPrice.setSumImMark(aDouble);
            quotedPrice.setIsPrize(null == aDouble ? OrderConstant.State.STOP : OrderConstant.State.START);
            if (!CollectionUtils.isEmpty(collect) && collect.get(quotedPrice.getId()) != null) {
                quotedPrice.setAwardCount(collect.get(quotedPrice.getId()).getAwardCount());
            } else {
                quotedPrice.setAwardCount(0);
            }
        });
    }

    /**
     * 统计报价单中标总金额
     */
    private Map<Long, Double> countSumImkPrice(List<PriceParityDetailsResponse> priceParityInfos) {
        if (CollectionUtils.isEmpty(priceParityInfos)) {
            return null;
        }
        Map<Long, Double> map = new HashMap<>();
        priceParityInfos.forEach(priceParityInfo -> {
            double sumPrice = 0.0;
            List<AwardInfoResponse> awardInfoResponses = priceParityInfo.getAwardInfoResponses();
            for (AwardInfoResponse awardInfo : awardInfoResponses) {
                if (null != awardInfo.getIsPrize() && OrderConstant.State.START.equals(awardInfo.getIsPrize())) {
                    sumPrice += awardInfo.getTaxPrice() * awardInfo.getAwardTaxProbability() / 100;
                }
            }
            if (0 < sumPrice) {
                map.put(priceParityInfo.getId(), BigDecimal.valueOf(sumPrice).setScale(2, RoundingMode.HALF_UP).doubleValue());
            }
        });
        return map;
    }


}
